#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include <QNetworkInterface>
#include <QDebug>
#include <QPainter>
#include <QDesktopWidget>
#include <QMessageBox>

class PainterFilter : public QObject
{
public:
    explicit PainterFilter(QObject *parent = nullptr) : QObject(parent) {}

    void updateImage(const QPixmap& pixmap){
        _pixmap = pixmap;
        QWidget* widget = dynamic_cast<QWidget*>(parent());
        if(widget){
            widget->update();
        }
    }

    bool isfirst(){
        return _pixmap.isNull();
    }
    void setClientPtr(MainWindow* client){_client = client;}
protected:
    bool eventFilter(QObject *obj, QEvent *event) override
    {
        if (event->type() == QEvent::Paint && !_pixmap.isNull()) {
            QWidget* widget = dynamic_cast<QWidget*>(obj==nullptr?parent():obj);
            if(widget){
                QPainter painter(widget);
                painter.drawPixmap(QRect(QPoint(0,0),widget->size()),_pixmap);
            }
            return true;
        }else if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            // 获取鼠标点击事件的全局坐标
            QPoint globalPos = mouseEvent->pos();//mouseEvent->globalPos();
            if(_client->getClientPtr()){
                _client->getClientPtr()->writeCmd(QString("%1:%2:%3")
                                  .arg("move")
                                  .arg(globalPos.x())
                                  .arg(globalPos.y()));
            }
        }
        return QObject::eventFilter(obj, event);
    }
private:
    QPixmap _pixmap;
    MainWindow* _client;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , _client(nullptr)
{
    ui->setupUi(this);
    m_ThreadServer = nullptr;

    ui->stop->hide();
    ui->close->hide();
    ui->stops->hide();
    ui->server_ip2->hide();
    _painter = new PainterFilter(ui->centralwidget);
    _painter->setClientPtr(this);
    ui->centralwidget->installEventFilter(_painter);

    QStringList strIps;
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interface, interfaces) {
        foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                //qDebug() << "ipv4 address:" << entry.ip().toString();
                if(entry.ip().toString() == "127.0.0.1"){
                    continue;
                }
                strIps.push_back(entry.ip().toString());
            }
            else if (entry.ip().protocol() == QAbstractSocket::IPv6Protocol) {
                //qDebug() << "ipv6 address:" << entry.ip().toString();
            }
        }
    }
    ui->server_ip2->setVisible(strIps.size() > 1);
    if(strIps.size() > 0){
        if(strIps.size() <= 2){
            ui->server_ip->setText(strIps.first());
            if(strIps.size() > 1){
                ui->server_ip2->setText(strIps.at(1));
            }
        }else{
            ui->server_ip->setText(strIps.first() + ";" + strIps.at(1));
            if(strIps.size() > 3){
                ui->server_ip2->setText(strIps.at(2) + ";" + strIps.at(3));
            }else{
                ui->server_ip2->setText(strIps.at(2));
            }
        }
    }else{
        ui->server_ip->setText("0.0.0.0");
    }

#ifndef Q_OS_LINUX
    ui->ip->setText("127.0.0.1");
#else
     ui->ip->setText("192.168.31.100");
#endif
}

MainWindow::~MainWindow()
{qDebug()<<"MainWindow::~MainWindow";
    if(_client){
        on_stop_clicked();
    }
    if(m_ThreadServer != nullptr){
        m_ThreadServer->deleteLater();
        m_ThreadServer = nullptr;
    }
    delete ui;
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if(e->x() < 10 && e->y() > (height()-10)){
        if(ui->server->isHidden()){
            ui->client->show();
        }
    }
}

/**
 * @name    on_start_clicked
 * @brief   客户端打开
 * @param   void
 * @return  void
*/
void MainWindow::on_start_clicked()
{
    if(_client == nullptr){
        _client = new QRSCClient(this);
        connect(_client,&QRSCClient::onReceiveImage,this,[this](const QPixmap& image){
            if(_painter->isfirst()){
                //resize(image.size());
                QRect rc = QApplication::desktop()->availableGeometry();
                move(rc.center().x()-frameSize().width()/2,rc.center().y()-frameSize().height()/2);
            }
            _painter->updateImage(image);
        });
        connect(_client,&QTcpSocket::disconnected,this,[this]{
            if(ui->server->isHidden()){
                on_stop_clicked();
            }
        });
        connect(_client,&QTcpSocket::connected,this,[this]{
            if(!ui->server->isHidden()){
                ui->start->hide();
                ui->close->show();
                ui->stop->show();
                ui->ip->setEnabled(false);
                ui->port->setEnabled(false);
                ui->screen->setEnabled(false);
                ui->client->hide();
                ui->server->hide();
                ui->groupBox->hide();
            }else{
                _client->stop();
            }
        });
    }
    _client->start(ui->ip->text(),ui->port->text().toInt());
}

/**
 * @name    on_stop_clicked
 * @brief   客户端关闭
 * @param   void
 * @return  void
*/
void MainWindow::on_stop_clicked()
{qDebug()<<"关闭";
    _painter->updateImage(QPixmap());
    _client->stop();
    ui->start->show();
    ui->close->hide();
    ui->stop->hide();
    ui->ip->setEnabled(true);
    ui->port->setEnabled(true);
    ui->screen->setEnabled(true);
    ui->client->show();
    ui->server->show();
    ui->groupBox->show();
}

void MainWindow::on_close_clicked()
{
    ui->client->hide();
}

/**
 * @name    on_starts_clicked
 * @brief   服务器打开
 * @param   void
 * @return  void
*/
void MainWindow::on_starts_clicked()
{
    if(m_ThreadServer == nullptr){
        m_ThreadServer = new QRSCServerThread();
    }
    m_ThreadServer->setQuality(ui->quality->value());
    if(m_ThreadServer->startServer(54520)){
        ui->client->hide();
        ui->starts->hide();
        ui->quality->setEnabled(false);
        ui->stops->show();
        ui->server_port->setText(QString::number(m_ThreadServer->serverPort()));qDebug()<<"port="<<m_ThreadServer->serverPort();
    }
}

/**
 * @name    on_stops_clicked
 * @brief   服务器关闭
 * @param   void
 * @return  void
*/
void MainWindow::on_stops_clicked()
{
    ui->client->show();
    ui->starts->show();
    ui->quality->setEnabled(true);
    ui->stops->hide();

    if(m_ThreadServer != nullptr){
        m_ThreadServer->stopServer();
        ui->server_port->setText("00000");
        m_ThreadServer->deleteLater();
        m_ThreadServer = nullptr;
    }
}


void MainWindow::on_pushButton_clicked()
{
    QMessageBox::warning(nullptr,"标题","内容");
}

void MainWindow::on_btnLocal_clicked()
{
    ui->ip->setText("127.0.0.1");
}

void MainWindow::on_btnRemote_clicked()
{
    ui->ip->setText("192.168.31.100");
}
